#include"Stack.h"

Stack::Stack(int n)
{
	_a = (STDataType*)malloc(sizeof(STDataType) * n);
	_top = 0;
	_capacity = n;
}
Stack::~Stack()
{
	free(_a);
	_a = nullptr;
	_top = 0;
	_capacity = 0;
}

//void Stack::Init()
//{
//	_a = nullptr;
//	_top = 0;
//	_capacity = 0;
//}
//void Stack::Destroy()
//{
//	free(_a);
//	_a = nullptr;
//	_top = 0;
//	_capacity = 0;
//}
void Stack::Push(STDataType x)
{
	if (_top == _capacity)
	{
		int newcapacity = _capacity == 0 ? 4 : 2 * _capacity;
		STDataType* tmp = (STDataType*)realloc(_a, sizeof(STDataType) * newcapacity);
		if (tmp == nullptr)
		{
			perror("realloc fail");
			return;
		}
		_capacity = newcapacity;
		_a = tmp;
	}
	_a[_top++] = x;
}
void Stack::Pop()
{
	assert(_top);
	_top--;
}
STDataType Stack::Top()
{
	assert(_top);
	return _a[_top - 1];
}
bool Stack::Empty()
{
	return _top == 0;
}
int Stack::Size()
{
	return _top;
}